import { pageCuesTopic, pageCuesTopicInit } from '@/services/api/api-cues-topic';
import {
  LightFilter,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormTreeSelect,
  ProTable,
} from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Input, Space, Tag, TreeSelect } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableTableTopicRenderDetails from './TableTopicRenderDetails';
import ProList from '@ant-design/pro-list';
import { parse } from '@/utils/historyUtils';
interface TableTopicRenderProps {
  mode: number;
  loading: boolean;
  industryIds: any[];
  actionRef?: ActionType;
  onRefurbish: () => void;
}

const TableTopicRender: React.FC<TableTopicRenderProps> = (props) => {
  const { actionRef } = props;
  const userRef = useRef<ActionType>();
  const userRefList = useRef<ActionType>();
  const access = useAccess();

  const [topicId, setTopicIdState] = useState()

  useEffect(() => {
    if (props.loading) {
      userRef.current?.reload();
      userRefList.current?.reload();
      props.onRefurbish();
    }
  }, [props.loading]);

  useEffect(() => {
    const { topicId } = parse(location.search) as { topicId: string };
    setTopicIdState(topicId);
  }, [])

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          key: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pageCuesTopic({ mode: props.mode, ...params, ...queryParam, });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  /**
   * 查询单位
   */
  const [queryOrganizations, setQueryOrganizationsState] = useState<any>();

  /**
   * 加载 页面初始化信息
   * @param key
   */
  const loadPageCuesTopicInitData = async () => {
    try {
      const response = await pageCuesTopicInit({ mode: props.mode });
      if (response.code === 0) {
        setQueryOrganizationsState(readyTreeData(response.data.queryOrganizations));
      }
    } catch (error) { }
  };
  useEffect(() => {
    loadPageCuesTopicInitData();
  }, []);

  return (
    <>
      <Input.Search
        placeholder="查询标题1"
        enterButton="搜索"
        allowClear
        style={{ maxWidth: 522, width: '100%', marginTop: 5 }}
        onChange={(e) => {
          setQueryParamState({ ...queryParam, name: e.target.value });
        }}
        onSearch={(value) => {
          userRefList.current?.reset();
        }}
      />
      <LightFilter
        // initialValues={{ run: 2 }}
        onValuesChange={(value) => {
          setQueryParamState(value);
          userRefList.current?.reset();
        }}
      >
        <ProFormSelect
          name="grades"
          label="选题分类"
          mode="multiple"
          options={[
            {
              label: '重大',
              value: 1,
            },
            {
              label: '重要',
              value: 2,
            },
            {
              label: '一般',
              value: 3,
            },
          ]}
        />
        <ProFormSelect
          hidden={!access.线索征集x配置x提供者}
          name="isView"
          label="阅读"
          options={[
            {
              label: '是',
              value: 1,
            },
            {
              label: '否',
              value: 0,
            },
          ]}
        />
        <ProFormSelect
          hidden={!access.线索征集x配置x提供者}
          name="isSubmit"
          label="报送"
          options={[
            {
              label: '是',
              value: 1,
            },
            {
              label: '否',
              value: 0,
            },
          ]}
        />
        {/* <ProFormDateRangePicker name="deadlineTimes" label="截止范围" allowClear /> */}
        {/* <ProFormTreeSelect
          name="createdOrganizationIds"
          label="发布单位"
          width="xl"
          placeholder="选择单位"
          fieldProps={{
            treeData: queryOrganizations,
            treeCheckable: true,
            showCheckedStrategy: TreeSelect.SHOW_PARENT,
          }}
        /> */}
      </LightFilter>
      <ProList<CuesTopicData.TopicPage>
        header={false}
        headerTitle={false}
        ghost={true}
        // ghost={false}
        // itemCardProps={{
        //   ghost: false,
        // }}
        pagination={{
          defaultPageSize: 8,
          showSizeChanger: false,
          showTotal: false,
          style: { textAlign: 'center' },
        }}
        className='topicRender'
        style={{ marginTop: 10 }}
        actionRef={userRefList}
        request={request}
        showActions="hover"
        grid={{ gutter: 18, column: 1 }}
        onItem={(record: any) => {
          return {
            onMouseEnter: () => { },
            onClick: () => { },
          };
        }}
        renderItem={(item: CuesTopicData.TopicPage, index: number) => {
          return (
            <TableTableTopicRenderDetails
              topicId={topicId}
              item={item}
              onRefurbish={() => {
                userRef.current?.reload();
                userRefList.current?.reload();
              }}
              triggerMode="card"
              title={item.name}
            />
          );
        }}
        rowKey={'id'}
        toolBarRender={false}
      />
      {/* <ProTable<CuesTopicData.TopicPage>
        columns={[
          {
            title: '选题标题',
            key: 'name',
            dataIndex: 'name',
            width: '180px',
            search: false,
            ellipsis: true,
            render: (_, row) => (
              <>
                {row.isLinkage === 1 && (
                  <Tag color="orange">
                    {row.linkageType === 1
                      ? '协助媒体'
                      : row.linkageType === 2
                        ? '联动部门'
                        : row.linkageType === 3
                          ? '协助媒体、单位'
                          : '暂无'}
                  </Tag>
                )}
                <Tag color={row.grade === 1 ? '#f50' : row.grade === 2 ? '#ffd591' : '#2db7f5'}>
                  {row.grade === 1 ? '重大' : row.grade === 2 ? '重要' : '一般'}
                </Tag>
                <Tag color={row.run === 1 ? 'green' : row.run === 2 ? 'red' : 'orange'}>
                  {row.run === 1 ? '进行中' : row.run === 2 ? '已结束' : '已暂停'}
                </Tag>
                {row.showView === 1 && row.isView === 0 ? (
                  <Tag color="red">未阅读</Tag>
                ) : row.showSubmit === 1 && row.isSubmit === 0 ? (
                  <Tag color="red">未报送</Tag>
                ) : (
                  <></>
                )}
                <TableTableTopicRenderDetails
                  item={row}
                  onRefurbish={() => {
                    userRef.current?.reload();
                    userRefList.current?.reload();
                  }}
                  triggerMode="title"
                  title={row.name}
                />
              </>
            ),
          },
          {
            title: '报送单位',
            dataIndex: 'createdOrganizationAvatar',
            key: 'createdOrganizationAvatar',
            width: '100px',
            valueType: 'avatar',
            render: (dom, row) => (
              <Space>
                <span>{dom}</span>
                {row.createdOrganizationName}
              </Space>
            ),
          },
          {
            title: '截止时间',
            dataIndex: 'deadlineTime',
            key: 'deadlineTime',
            width: '80px',
            align: 'center',
            valueType: 'dateTime',
          },
          {
            title: '报送线索',
            dataIndex: 'countSubmit',
            key: 'countSubmit',
            width: '50px',
            align: 'center',
            search: false,
          },
          {
            title: '报送单位',
            dataIndex: 'countSubmitOrganization',
            key: 'countSubmitOrganization',
            width: '50px',
            align: 'center',
            hideInTable: access.线索征集x配置x提供者,
            search: false,
          },
          {
            title: '阅读情况',
            hideInSearch: true,
            hideInTable: access.线索征集x配置x提供者,
            dataIndex: 'receipt',
            key: 'receipt',
            valueType: 'avatar',
            width: '80px',
            align: 'center',
            search: false,
            render: (dom, record) => (<>
              <ReceiptReport id={record.id} receipt={record.receipt} onRefurbish={() => {
                userRef.current?.reload();
                userRefList.current?.reload();
              }} />
            </>),
          },
        ]}
        headerTitle={false}
        ghost={true}
        pagination={{
          defaultPageSize: 9,
          showSizeChanger: false,
        }}
        search={false}
        actionRef={userRef}
        request={requestTable}
        rowKey={'id'}
        toolbar={{
          search: {
            onChange: (e) => {
              setQueryParamState({ ...queryParam, name: e.target.value });
            },
            onSearch: (value) => {
              userRef.current?.reset();
            },
          },
          filter: (
            <LightFilter
              // initialValues={{ run: 2 }}
              onValuesChange={(value) => {
                setQueryParamState(value);
                userRef.current?.reset();
              }}
            >
              <ProFormSelect
                name="grades"
                label="分类"
                mode="multiple"
                options={[
                  {
                    label: '重大',
                    value: 1,
                  },
                  {
                    label: '重要',
                    value: 2,
                  },
                  {
                    label: '一般',
                    value: 3,
                  },
                ]}
              />
              <ProFormSelect
                hidden={!access.线索征集x配置x提供者}
                name="isView"
                label="阅读"
                options={[
                  {
                    label: '是',
                    value: 1,
                  },
                  {
                    label: '否',
                    value: 0,
                  },
                ]}
              />
              <ProFormSelect
                hidden={!access.线索征集x配置x提供者}
                name="isSubmit"
                label="报送"
                options={[
                  {
                    label: '是',
                    value: 1,
                  },
                  {
                    label: '否',
                    value: 0,
                  },
                ]}
              />
              <ProFormDateRangePicker name="deadlineTimes" label="截止范围" allowClear />

              <ProFormTreeSelect
                name="createdOrganizationIds"
                label="发布单位"
                width="xl"
                placeholder="选择单位"
                fieldProps={{
                  treeData: queryOrganizations,
                  treeCheckable: true,
                  showCheckedStrategy: TreeSelect.SHOW_PARENT,
                }}
              />
            </LightFilter>
          ),
        }}
      /> */}
    </>
  );
};

export default TableTopicRender;
